﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common.Utilities.OpenXml
{
	/// <summary>
	/// Encapsulates the pivot chart part.
	/// </summary>
	public class PivotTable : PackagePartBase
	{
		private PivotTable(PackageHelper package, Uri uri)
			: base(package, uri)
		{ }

		/// <summary>
		/// Creates a new pivot table part.
		/// </summary>
		/// <param name="package">The package to creat the part in.</param>
		/// <param name="name">The name of the new part to create.</param>
		/// <param name="data">The data to use when initializing the part's content.</param>
		/// <param name="pivotCacheDefinition">The PivotCacheDefinition part referenced by the new part.</param>
		/// <returns>A new instance of a PivotTable object.</returns>
		public static PivotTable Create(PackageHelper package, string name, byte[] data, PivotCacheDefinition pivotCacheDefinition)
		{
			// create PivotTable package part
			Uri pivotTableUri =
				new Uri(string.Format("/xl/pivotTables/{0}.xml", name),
						UriKind.Relative);
			package.CreateNewPart(pivotTableUri,
				"application/vnd.openxmlformats-" +
				"officedocument.spreadsheetml.pivotTable+xml",
				data);

			// create the relationship to the data
			package.CreateInternalRelationship(pivotTableUri,
				pivotCacheDefinition.Uri,
				"http://schemas.openxmlformats.org/officeDocument/" +
				"2006/relationships/pivotCacheDefinition");

			// return the new object
			return new PivotTable(package, pivotTableUri);
		}

		/// <summary>
		/// Sets the cache id of the referenced pivot cache definition.
		/// </summary>
		/// <param name="cacheId">The cache id of the pivot cache definition for this pivot table.</param>
		public void SetDefinitionCacheId(int cacheId)
		{
			// set the cacheId attribute of the document element
			base.PackageData.DocumentElement.SetAttribute(
				"cacheId", cacheId.ToString());
		}
	}
}
